import { createRequire } from "module";
import { fileURLToPath } from "url";
const require = createRequire(import.meta.url);

const { defineConfig, build } = require("vite");
const path = require("path");
const vue = require("@vitejs/plugin-vue");
const vueJsx = require("@vitejs/plugin-vue-jsx");
const fsExtra = require("fs-extra");
const fs = require("fs");

const _fileName = fileURLToPath(import.meta.url);
const __dirname = path.dirname(_fileName);

// 入口文件
const entryFile = path.resolve(__dirname, "./entry.ts");
// 输出目录
const outputDir = path.resolve(__dirname, "../build");
// 组件目录
const componentsDir = path.resolve(__dirname, "../src");

const baseConfig = defineConfig({
	baseConfig: false,
	publicDir: false,
	plugins: [vue(), vueJsx()]
});

const rollupOptions = {
	external: ["vue", "vue-router"],
	output: {
		globals: {
			vue: "Vue"
		}
	}
};

// 全量构建
const buildAll = async () => {
	await build(
		defineConfig({
			...baseConfig,
			build: {
				rollupOptions,
				lib: {
					entry: entryFile,
					name: "sheep-ui",
					fileName: "sheep-ui",
					formats: ["es", "umd"]
				},
				outDir: outputDir
			}
		})
	);
};
// 单个打包
const buildSingle = async (name) => {
	await build(
		defineConfig({
			...baseConfig,
			build: {
				rollupOptions,
				lib: {
					entry: path.resolve(componentsDir, name),
					name: "index",
					fileName: "index",
					formats: ["es", "umd"]
				},
				outDir: path.resolve(outputDir, name)
			}
		})
	);
	createPackageJson(name);
};

const createPackageJson = (name) => {
	const fileStr = JSON.stringify({
		name: name ? name : "sheep-ui",
		version: "0.0.0",
		main: name ? "index.umd.js" : "sheep-ui.umd.js",
		module: name ? "index.js" : "sheep-ui.js",
		author: "杨村长",
		github: "",
		description: "羊村第一个组件库Sheep-UI，以后村里羊圈能不能建好就看它了！",
		repository: {
			type: "git",
			url: "git+https://github.com/57code/sheep-ui.git"
		},
		keywords: ["vue3", "组件库", "tsx", "UI"],
		license: "ISC",
		bugs: {
			url: "https://github.com/57code/sheep-ui/issues"
		}
	});
	// 存在包名称，给单组件生成package.json文件
	if (name) {
		fsExtra.outputFile(path.resolve(outputDir, name + "/" + "package.json"), fileStr, "utf-8");
	} else {
		fsExtra.outputFile(path.resolve(outputDir, "package.json"), fileStr, "utf-8");
	}
};

const buildLib = async () => {
	await buildAll();
	// 创建package.json
	createPackageJson();
	// 获取组件名称组成的数组
	fs.readdirSync(componentsDir)
		.filter((name) => {
			const componentDir = path.resolve(componentsDir, name);
			const isDir = fs.lstatSync(componentDir).isDirectory();
			return isDir && fs.readdirSync(componentDir).includes("index.ts");
		})
		.forEach((name) => {
			buildSingle(name);
		});
};

buildLib();
